package pt.compflow.client;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateOutputRepresentation extends OutputRepresentation {
	
	private String templateFile;
	private Map<String, Object> attributes;
	private Configuration cfg;

	public TemplateOutputRepresentation(Configuration cfg, MediaType mediaType, String templateFile, Map<String, Object> attributes) {
		super(mediaType);
		this.templateFile = templateFile;
		this.attributes = attributes;
		this.cfg = cfg;
	}
	
	@Override
	public CharacterSet getCharacterSet() {
		return CharacterSet.UTF_8;
	}
	
	@Override
	public void write(OutputStream out) throws IOException {
		Template template = cfg.getTemplate(templateFile);

	    Writer writer = new OutputStreamWriter(out);
	    try {
			template.process(attributes, writer);
		} catch (TemplateException e) {
			throw new RuntimeException(e);
		}
	}

}
